<template>
  <view class="appointment-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-button" @click="goBack">
      </view>
      <view class="page-title">预约回收</view>
      <view class="placeholder"></view>
    </view>

    <!-- 回收类型选择 -->
    <view class="section">
      <view class="section-title">回收类型</view>
      <view class="category-grid">
        <view class="category-item" v-for="(item, index) in recycleCategories" :key="index"
          :class="{ active: selectedCategories.includes(item.id) }" @click="toggleCategory(item.id)">
          <view class="category-icon">
            <image :src="item.icon" mode="aspectFit"></image>
          </view>
          <view class="category-content">
            <view class="category-name">{{ item.name }}</view>
            <view class="category-desc">{{ item.description }}</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 预约时间 -->
    <view class="section">
      <view class="section-title">预约时间</view>
      <picker mode="date" :value="selectedDate" @change="onDateChange" start="2023-06-01">
        <view class="date-picker">
          <text class="date-icon">📅</text>
          <text class="date-placeholder" v-if="!selectedDate">请选择日期</text>
          <text class="selected-date" v-else>{{ formatDate(selectedDate) }}</text>
          <text class="calendar-icon">🗓️</text>
        </view>
      </picker>

      <!-- 时间段选择 -->
      <view class="section-subtitle">时间段</view>
      <view class="time-slots">
        <view class="time-slot" v-for="(slot, index) in timeSlots" :key="index"
          :class="{ active: selectedTimeSlot === slot.value }" @click="selectTimeSlot(slot.value)">
          {{ slot.label }}
        </view>
      </view>
    </view>

    <!-- 回收地址 -->
    <view class="section">
      <view class="section-title">回收地址</view>
      <view class="address-list">
        <view class="address-item" v-for="(address, index) in addresses" :key="index"
          :class="{ active: selectedAddressId === address.id }" @click="selectAddress(address.id)">
          <view class="address-marker" :class="{ active: selectedAddressId === address.id }">
            <text class="marker-icon">📍</text>
          </view>
          <view class="address-content">
            <view class="address-header">
              <text class="address-name">{{ address.name }}</text>
              <text class="address-phone">{{ address.phone }}</text>
            </view>
            <view class="address-detail">{{ address.detail }}</view>
          </view>
        </view>
      </view>
      <view class="add-address" @click="addNewAddress">
        <text class="add-icon">+</text>
        <text class="add-text">新增/修改地址</text>
      </view>
    </view>

    <!-- 物品信息 -->
    <view class="section">
      <view class="section-title">物品信息</view>
      <view class="weight-input">
        <view class="input-icon">📦</view>
        <input type="digit" v-model="estimatedWeight" placeholder="请输入预估重量" class="weight-field" />
        <view class="input-unit">(kg)</view>
      </view>
    </view>

    <!-- 备注信息 -->
    <view class="section">
      <view class="section-title">备注信息</view>
      <textarea class="remark-input" v-model="remark" placeholder="如有特殊要求，请在此说明"></textarea>
    </view>

    <!-- 回收须知 -->
    <view class="section notice-section">
      <view class="section-title">回收须知</view>
      <view class="notice-list">
        <view class="notice-item" v-for="(item, index) in noticeItems" :key="index">
          <text class="notice-dot">•</text>
          <text class="notice-text">{{ item }}</text>
        </view>
      </view>
    </view>

    <!-- 预约提交区域 -->
    <view class="submit-area">
      <view class="estimated-points">
        <text class="points-label">预估积分:</text>
        <text class="points-value">{{ estimatedPoints }}</text>
      </view>
      <button class="submit-button" v-auth:tap.redirect="submitOrder">提交回收</button>
    </view>
  </view>
</template>

<script>
import Icon from '@/components/common/Icon.vue';
import authMixin from '../../mixins/auth-mixin.js';
import { checkLogin } from '../../utils/auth.js';

export default {
  components: {
    Icon
  },
  mixins: [authMixin],
  data() {
    return {
      // 回收分类
      recycleCategories: [
        {
          id: 1,
          name: '衣物回收',
          description: '衣服, 裤子, 外套等',
          icon: '/static/images/categories/clothes.svg'
        },
        {
          id: 2,
          name: '鞋包回收',
          description: '鞋子, 包包, 配饰等',
          icon: '/static/images/categories/bags.svg'
        },
        {
          id: 3,
          name: '家纺回收',
          description: '床单, 被套, 窗帘等',
          icon: '/static/images/categories/textiles.svg'
        },
        {
          id: 4,
          name: '玩具回收',
          description: '毛绒玩具, 塑料玩具等',
          icon: '/static/images/categories/toys.svg'
        }
      ],
      // 已选分类ID
      selectedCategories: [1],

      // 日期选择
      selectedDate: '',

      // 时间段选择
      timeSlots: [
        { label: '09:00-11:00', value: '09:00-11:00' },
        { label: '11:00-13:00', value: '11:00-13:00' },
        { label: '13:00-15:00', value: '13:00-15:00' },
        { label: '15:00-17:00', value: '15:00-17:00' },
        { label: '17:00-19:00', value: '17:00-19:00' }
      ],
      selectedTimeSlot: '',

      // 地址
      addresses: [
        {
          id: 1,
          name: '张三',
          phone: '13812345678',
          detail: '北京市朝阳区建国路88号公寓 3号楼 2单元 303室'
        },
        {
          id: 2,
          name: '李四',
          phone: '13987654321',
          detail: '北京市海淀区中关村大街1号科技大厦 B座 1001室'
        }
      ],
      selectedAddressId: 1,

      // 物品信息
      estimatedWeight: '',

      // 备注
      remark: '',

      // 回收须知
      noticeItems: [
        '请确保衣物干净、无破损',
        '回收员将在预约时间上门',
        '根据实际重量计算积分',
        '如需取消预约，请提前2小时'
      ],

      // 预估积分
      estimatedPoints: 50,

      // 当前用户是否已登录
      isLoggedIn: false
    };
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 切换分类选择
    toggleCategory(id) {
      const index = this.selectedCategories.indexOf(id);
      if (index > -1) {
        // 如果当前只有一个选择，不允许取消
        if (this.selectedCategories.length > 1) {
          this.selectedCategories.splice(index, 1);
        }
      } else {
        this.selectedCategories.push(id);
      }
      this.calculateEstimatedPoints();
    },

    // 显示日期选择器
    showDatePicker() {
      // 此方法已经不再使用，由picker组件的onDateChange替代
      console.log('此方法已弃用');
    },

    // 日期选择器变更事件
    onDateChange(e) {
      this.selectedDate = e.detail.value;
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const parts = dateString.split('-');
      if (parts.length === 3) {
        return `${parts[0]}/${parts[1]}/${parts[2]}`;
      }
      // 如果是Date对象格式化
      const date = new Date(dateString);
      if (!isNaN(date.getTime())) {
        return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
      }
      return dateString;
    },

    // 选择时间段
    selectTimeSlot(slot) {
      this.selectedTimeSlot = slot;
    },

    // 选择地址
    selectAddress(id) {
      this.selectedAddressId = id;
    },

    // 添加新地址
    addNewAddress() {
      // 使用混入的withAuth方法
      this.withAuth(() => {
        uni.navigateTo({
          url: '/pages/address/add'
        });
      })();
    },

    // 计算预估积分
    calculateEstimatedPoints() {
      if (!this.estimatedWeight || isNaN(parseFloat(this.estimatedWeight))) {
        this.estimatedPoints = 0;
        return;
      }

      // 简单计算：每公斤10积分
      const weight = parseFloat(this.estimatedWeight);
      this.estimatedPoints = Math.floor(weight * 10);
    },

    // 提交回收订单（需要登录权限）
    submitOrder() {
      // 使用权限检查工具检查登录状态
      if (!checkLogin()) return;

      // 表单验证
      if (!this.selectedAddress) {
        uni.showToast({
          title: '请选择回收地址',
          icon: 'none'
        });
        return;
      }

      if (!this.selectedDate) {
        uni.showToast({
          title: '请选择预约日期',
          icon: 'none'
        });
        return;
      }

      if (!this.selectedTimeSlot) {
        uni.showToast({
          title: '请选择预约时间段',
          icon: 'none'
        });
        return;
      }

      if (!this.estimatedWeight || parseFloat(this.estimatedWeight) <= 0) {
        uni.showToast({
          title: '请输入有效的预估重量',
          icon: 'none'
        });
        return;
      }

      // 构建订单数据
      const orderData = {
        address: this.selectedAddress,
        appointmentDate: this.selectedDate,
        appointmentTime: this.selectedTimeSlot,
        estimatedWeight: parseFloat(this.estimatedWeight),
        estimatedPoints: this.estimatedPoints,
        remark: this.remark,
        createTime: new Date().toISOString()
      };

      // 模拟提交到服务器
      uni.showLoading({
        title: '提交中...'
      });

      // 这里应该调用API提交数据
      setTimeout(() => {
        uni.hideLoading();

        // 成功后跳转到订单详情页
        uni.navigateTo({
          url: `/pages/recycle/order-detail?id=${Date.now()}`
        });

        // 显示成功提示
        uni.showToast({
          title: '预约成功',
          icon: 'success'
        });
      }, 2000);
    },

    // 初始化数据
    initData() {
      // 从本地存储加载最新的地址列表
      uni.getStorage({
        key: 'addressList',
        success: (res) => {
          if (res.data && res.data.length > 0) {
            this.addresses = res.data;

            // 如果当前选中的地址不在列表中，则选择默认地址或第一个地址
            const currentAddressExists = this.addresses.some(address => address.id === this.selectedAddressId);

            if (!currentAddressExists) {
              // 优先选择默认地址
              const defaultAddress = this.addresses.find(address => address.isDefault);
              if (defaultAddress) {
                this.selectedAddressId = defaultAddress.id;
              } else {
                // 否则选择第一个地址
                this.selectedAddressId = this.addresses[0].id;
              }
            }
          }
        }
      });
    },

    // 刷新登录状态
    onShow() {
      // 刷新登录状态
      this.isLoggedIn = this.isUserLoggedIn;

      // 从本地存储获取地址列表
      this.refreshAddressList();
    }
  },
  watch: {
    // 监听预估重量变化，计算积分
    estimatedWeight() {
      this.calculateEstimatedPoints();
    }
  },
  onLoad() {
    // 初始化数据
    this.initData();
  }
};
</script>

<style lang="scss">
@import '../../styles/global.scss';

.appointment-container {
  padding-bottom: 140rpx;
  background-color: $bg-color;
}

/* 头部导航 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: $card-bg;
  position: relative;
  border-bottom: 1rpx solid $border-light;

  .back-button {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .page-title {
    font-size: 36rpx;
    font-weight: bold;
    color: $text-black;
  }

  .placeholder {
    width: 60rpx;
  }
}

/* 内容区域 */
.section {
  background-color: $card-bg;
  margin: 20rpx 0;
  padding: 30rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
  }

  .section-subtitle {
    font-size: 28rpx;
    margin: 20rpx 0;
  }
}

/* 回收类型 */
.category-grid {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.category-item {
  border: 1rpx solid $border-color;
  border-radius: 10rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;

  &.active {
    border-color: $primary-green;
    background-color: $light-green;
  }

  .category-icon {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    justify-content: center;
    align-items: center;

    image {
      width: 50rpx;
      height: 50rpx;
    }
  }

  .category-content {
    margin-left: 20rpx;

    .category-name {
      font-size: 28rpx;
      font-weight: bold;
    }

    .category-desc {
      font-size: 24rpx;
      color: $text-light-gray;
      margin-top: 6rpx;
    }
  }
}

/* 日期选择 */
.date-picker {
  border: 1rpx solid $border-color;
  border-radius: 10rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;

  .date-icon {
    margin-right: 20rpx;
  }

  .date-placeholder {
    color: $text-light-gray;
    flex: 1;
  }

  .selected-date {
    flex: 1;
  }
}

/* 时间段 */
.time-slots {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.time-slot {
  border: 1rpx solid $border-color;
  border-radius: 10rpx;
  padding: 20rpx;
  text-align: center;

  &.active {
    border-color: $primary-green;
    background-color: $light-green;
    color: $primary-green;
  }
}

/* 地址列表 */
.address-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.address-item {
  border: 1rpx solid $border-color;
  border-radius: 10rpx;
  padding: 20rpx;
  display: flex;
  align-items: flex-start;

  &.active {
    border-color: $primary-green;
  }

  .address-marker {
    margin-right: 20rpx;

    &.active {
      color: $primary-green;
    }
  }

  .address-content {
    flex: 1;

    .address-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10rpx;

      .address-name {
        font-weight: bold;
      }
    }

    .address-detail {
      font-size: 26rpx;
      color: $text-gray;
    }
  }
}

.add-address {
  display: flex;
  align-items: center;
  color: $primary-green;

  .add-icon {
    margin-right: 10rpx;
  }
}

/* 物品信息 */
.weight-input {
  border: 1rpx solid $border-color;
  border-radius: 10rpx;
  padding: 20rpx;
  display: flex;
  align-items: center;

  .input-icon {
    margin-right: 20rpx;
  }

  .weight-field {
    flex: 1;
  }

  .input-unit {
    color: $text-light-gray;
  }
}

/* 备注信息 */
.remark-input {
  border: 1rpx solid $border-color;
  border-radius: 10rpx;
  padding: 20rpx;
  width: 100%;
  height: 200rpx;
  box-sizing: border-box;
}

/* 回收须知 */
.notice-section {
  background-color: $status-processing-bg;
}

.notice-list {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.notice-item {
  display: flex;

  .notice-dot {
    margin-right: 10rpx;
  }

  .notice-text {
    color: $points-orange;
  }
}

/* 提交区域 */
.submit-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: $card-bg;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .estimated-points {
    display: flex;
    flex-direction: column;
    align-items: flex-start;

    .points-label {
      font-size: 28rpx;
      color: $text-black;
      margin-bottom: 6rpx;
    }

    .points-value {
      font-size: 36rpx;
      font-weight: bold;
      color: $primary-green;
    }
  }

  .submit-button {
    background-color: $primary-green;
    color: $text-white;
    padding: 15rpx 40rpx;
    border-radius: 12rpx;
    font-size: 30rpx;
    min-width: 180rpx;
    text-align: center;
    margin-right: 0;
    margin-left: 0;
    box-shadow: $button-shadow;
  }
}
</style>